package com.tus.util;

import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;

@Slf4j
public class ChecksumValidator {

    /**
     * 校验文件完整性
     *
     * @param filePath
     * @param algorithm
     * @param expectedChecksum
     * @return
     */
    public static boolean validate(String filePath, String algorithm, String expectedChecksum) {
        try (InputStream is = Files.newInputStream(Paths.get(filePath))) {
            MessageDigest md = MessageDigest.getInstance(algorithm.toUpperCase());
            byte[] buffer = new byte[8192];
            int read;
            while ((read = is.read(buffer)) != -1) {
                md.update(buffer, 0, read);
            }
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) sb.append(String.format("%02x", b));
            return sb.toString().equalsIgnoreCase(expectedChecksum);
        } catch (Exception e) {
            log.error("Checksum error", e);
            return false;
        }
    }
}